import Request from './wakary-request.js'

import _url from '@/utils/url.js'

const config = {
	baseUrl: ""
}

const reqInterceptor = async (options) => {
	options.url = _url(options.url);
	console.log("提交地址",options.url);
	delete options.header.Authorization
	return options
}

const resInterceptor = (response, conf = {}) => {
	const statusCode = response.statusCode
	// response log
	_responseLog(response, conf);


	// response interceptor
	if (statusCode >= 200 && statusCode < 300) { //成功
		const res = response.data

		// if the custom code is not 20000, it is judged as an error.
		if (res.code === 0) {
			console.log("查看", res.data);
			return res.data;
		} else {
			uni.showToast({
				title: res.msg || 'Error',
				duration: 2000
			});
			return false
		}
	} else if (statusCode === 500) {
		uni.showToast({
			title: response.errMsg || 'Error',
			duration: 2000
		});
		return false
	} else {
		uni.showToast({
			title: response.errMsg || 'Error',
			duration: 2000
		});
		return false
	}
}

const req = new Request(config, reqInterceptor, resInterceptor)

// response log
function _responseLog(res, conf = {}) {
	let _statusCode = res.statusCode;
	if (process.env.NODE_ENV === 'development') {
		console.log("地址: " + conf.url)
		console.log("结果: " + JSON.stringify(res))
	}
	//TODO into log server
	if (_statusCode === 500) {
		createAppFeed({
			title: '500: 服务器错误',
			detail: conf.url,
			version: 'v1'
		})
	}
}

export default req;
